package com.pearadmin.pro.modules.paper.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pearadmin.pro.common.aop.annotation.Log;
import com.pearadmin.pro.common.constant.ControllerConstant;
import com.pearadmin.pro.common.web.base.BaseController;
import com.pearadmin.pro.common.web.domain.Result;
import com.pearadmin.pro.modules.examUtils.PagingReqDTO;
import com.pearadmin.pro.modules.examUtils.dto.BaseIdReqDTO;
import com.pearadmin.pro.modules.examUtils.dto.BaseIdRespDTO;
import com.pearadmin.pro.modules.examUtils.dto.BaseIdsReqDTO;
import com.pearadmin.pro.modules.examUtils.excel.ExportExcel;
import com.pearadmin.pro.modules.examUtils.excel.ImportExcel;
import com.pearadmin.pro.modules.examUtils.exception.ServiceException;
import com.pearadmin.pro.modules.paper.dto.QuDTO;
import com.pearadmin.pro.modules.paper.dto.export.QuExportDTO;
import com.pearadmin.pro.modules.paper.dto.ext.QuDetailDTO;
import com.pearadmin.pro.modules.paper.dto.request.QuQueryReqDTO;
import com.pearadmin.pro.modules.paper.service.QuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 问题题目控制器
 * @author ZhouXingYun
 * @date 2022/5/25 15:15
 */
@Api(tags = {"问题题目"})
@RestController
@RequestMapping(ControllerConstant.PREFIX_SYS + "qu")
public class QuController extends BaseController {
    @Autowired
    private QuService baseService;


    /**
     * 查找单个试题详情
     *
     * @param reqDTO
     * @return
     */
    @ApiOperation(value = "查找单个试题详情")
    @Log(title = "查找单个试题详情")
    @RequestMapping(value = "/detail", method = {RequestMethod.POST})
    public Result<QuDetailDTO> detail(@RequestBody BaseIdReqDTO reqDTO) {
        QuDetailDTO dto = baseService.detail(reqDTO.getId());
        return success(dto);
    }

  /**
   * 试卷分页查找
   * @author ZhouXingYun
   * @date 2022/5/30 19:54
   * @param reqDTO
   * @return com.pearadmin.pro.common.web.domain.Result<com.baomidou.mybatisplus.core.metadata.IPage<com.pearadmin.pro.modules.paper.dto.QuDTO>>
   */
    @ApiOperation(value = "试卷分页查找")
    @Log(title = "试卷分页查找")
    @RequestMapping(value = "/paging", method = {RequestMethod.POST})
    public Result<IPage<QuDTO>> paging(@RequestBody PagingReqDTO<QuQueryReqDTO> reqDTO) {

        //分页查询并转换
        IPage<QuDTO> page = baseService.paging(reqDTO);
        return success(page);
    }

    /**
     * 添加或修改试题
     * @author ZhouXingYun
     * @date 2022/6/1 18:16
     * @param reqDTO
     * @return ApiRest<BaseIdRespDTO>
     */
    @ApiOperation(value = "添加或修改试题")
    @Log(title = "添加或修改试题")
    @RequestMapping(value = "/save", method = {RequestMethod.POST})
    public Result<BaseIdRespDTO> save(@RequestBody QuDetailDTO reqDTO) {
        baseService.save(reqDTO);
        return success();
    }

    /**
     * 批量删除试题
     *
     * @param reqDTO
     * @return
     */
    @ApiOperation(value = "批量删除试题")
    @Log(title = "批量删除试题")
    @RequestMapping(value = "/delete", method = {RequestMethod.DELETE})
    public Result edit(@RequestBody BaseIdsReqDTO reqDTO) {
        //根据ID删除
        baseService.removeByIds(reqDTO.getIds());
        return super.success();
    }
    /**
     * 导出题目列表
     */
    @ResponseBody
    @Log(title = "导出题目列表")
    @ApiOperation(value = "导出题目列表")
    @RequestMapping(value = "/export")
    public void exportFile(HttpServletResponse response, @RequestBody QuQueryReqDTO reqDTO) {

        // 导出文件名
        String fileName = "导出的试题-" + System.currentTimeMillis() + ".xlsx";

        try {

            int no = 0;
            String quId = "";
            List<QuExportDTO> list = baseService.listForExport(reqDTO);
            for (QuExportDTO item : list) {
                if (!quId.equals(item.getQId())) {
                    quId = item.getQId();
                    no += 1;
                } else {
                    item.setQuType("0");
                    item.setQContent("");
                    item.setQAnalysis("");
                    item.setRepoList(null);
                    item.setQImage("");
                    item.setQVideo("");
                }
                item.setNo(String.valueOf(no));
            }
            new ExportExcel("试题", QuExportDTO.class).setDataList(list).write(response, fileName).dispose();
//            return success();
        } catch (Exception e) {
            e.printStackTrace();
//            return failure(e.getMessage());
        }
    }


    /**
     * 导入题目列表
     *
     * @param file
     * @return
     */
    @ResponseBody
    @Log(title = "导入题目列表")
    @ApiOperation(value = "导入题目列表")
    @RequestMapping(value = "/import")
    public Result importFile(@RequestParam("file") MultipartFile file) {

        try {

            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<QuExportDTO> list = ei.getDataList(QuExportDTO.class);

            // 校验数据
            this.checkExcel(list);

            // 导入数据条数
            baseService.importExcel(list);

            // 导入成功
            return super.success();

        } catch (IOException e) {

        } catch (InvalidFormatException e) {

        } catch (IllegalAccessException e) {

        } catch (InstantiationException e) {

        }

        return failure();
    }

    /**
     * 校验Excel
     *
     * @param list
     * @throws Exception
     */
    private void checkExcel(List<QuExportDTO> list) throws ServiceException {

        // 约定第三行开始导入
        int line = 3;
        StringBuffer sb = new StringBuffer();

        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException(1, "您导入的数据似乎是一个空表格！");
        }

        Integer quNo = null;
        for (QuExportDTO item : list) {

            System.out.println(item.getNo());
            if (StringUtils.isBlank(item.getNo())) {
                line++;
                continue;
            }

            System.out.println(item.getQContent());
            Integer no;

            try {
                no = Integer.parseInt(item.getNo());
            } catch (Exception e) {
                line++;
                continue;
            }

            if (no == null) {
                sb.append("第" + line + "行，题目序号不能为空！<br>");
            }

            if (quNo == null || !quNo.equals(no)) {

                if (item.getQuType() == null) {
                    sb.append("第" + line + "行，题目类型不能为空<br>");
                }

                if (StringUtils.isBlank(item.getQContent())) {
                    sb.append("第" + line + "行，题目内容不能为空<br>");
                }

                if (CollectionUtils.isEmpty(item.getRepoList())) {
                    sb.append("第" + line + "行，题目必须包含一个题库<br>");
                }
            }

            if (StringUtils.isBlank(item.getAIsRight())) {
                sb.append("第" + line + "行，选项是否正确不能为空<br>");
            }

            if (StringUtils.isBlank(item.getAContent()) && StringUtils.isBlank(item.getAImage())) {
                sb.append("第" + line + "行，选项内容和选项图片必须有一个不为空<br>");
            }

            quNo = no;
            line++;
        }

        // 存在错误
        if (!"".equals(sb.toString())) {
            throw new ServiceException(1, sb.toString());
        }
    }

}
